import {ElMessage, ElMessageBox, ElNotification} from 'element-plus';
import request from '/@/utils/request';

export const cloud_file_download_url = "http://172.25.100.252:8005/api/cloud/file/download/";

export interface IDownLoadFileParams {
    annexId: string,
    fileFormat: string,
    fileName?: string,
    url?: string
}

export const downloadFile = (params: IDownLoadFileParams) => {
    if (isEmpty(params.annexId) || isEmpty(params.fileFormat)) {
        ElMessage({message: "下载失败！", type: 'warning'})
        return;
    }

    if (isEmpty(params.url)) {
        params.url = cloud_file_download_url;
    }

    let fileFormatOption = {
        doc: "application/msword",
        txt: "text/plain",
        docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        xls: "application/vnd.ms-excel",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        jpg: "image/jpeg",
        png: "image/png",
        ppt: "application/vnd.ms-powerpoint",
        pdf: "application/pdf",
        zip: "application/zip",
    }

    request({
        url: params.url + params.annexId,
        method: 'post',
        responseType: 'blob',
    }).then((res) => {
        let suffix = params.fileFormat.slice(1, params.fileFormat.length);
        let fileType = fileFormatOption[suffix];
        if (isEmpty(fileType)) {
            fileType = fileFormatOption["zip"];
        }
        let blob = new Blob([res], {type: fileType});
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = window.URL.createObjectURL(blob);
        link.download = isEmpty(params.fileName) ? '附件' : params.fileName;
        document.body.appendChild(link);
        link.click();
    });
}

const isEmpty = (value: any) => {
    if (value === '' || value == null || value == undefined) {
        return true
    }
    return false
}